/*
	Copyright 2012 Google Inc. All Rights Reserved.

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	    http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.package main
*/

package main

import (
	"gominion_server/gominionbase"
	"fmt"
	"hash/fnv"
	"io"
	"common"
	"net"
)

var games map[uint64]gominionbase.Game
var players map[uint64][]gominionbase.Player

func init() {
	games = make(map[uint64]gominionbase.Game)
	players = make(map[uint64][]gominionbase.Player)
}

func processPlayer(player gominionbase.Player) bool {
        h := fnv.New64()
        io.WriteString(h,player.Name)
        key := h.Sum64()
        _, ok := players[key]
        if ok {
                for i := range players[key] {
                        if players[key][i].Name == player.Name {
                                return false
                        }
                }
        }
        players[key] = append(players[key],player)
        return true
}

func initConnection(conn net.Conn) {
        message, readErr := common.ReadMessage(conn)
        if readErr != nil {
                fmt.Println(readErr.Error())
                return
        }
        connect, ok := message.(common.Connect)
	if ok == false {
		fmt.Printf("Received wrong connection message.")
		return
	}
	player := gominionbase.Player{Name: connect.Nickname,Status: connect.Status}
        fmt.Printf("Player connected with name %v and status %v\n", player.Name, player.Status)
        if !processPlayer(player) {
                fmt.Println("Duplicate player name.\n")
                return
        }
        common.ConnectionLoop(conn,player)
}

func main() {
	listener, err := net.Listen("tcp",":13610")
	if err != nil {
		//TODO(ebehar@google.com): Handle error
	}
	for {
		conn, err := listener.Accept()
		if err != nil {
			//TODO(ebehar@google.com): Handle error
		} else {
			go initConnection(conn)
		}
	}
}
